package com.hbk.service.impl;

import com.hbk.base.common.CommonResult;
import com.hbk.base.common.Ref;
import com.hbk.base.util.TimeUtil;
import com.hbk.entity.SysConfigItem;
import com.hbk.mapper.SysConfigItemMapper;
import com.hbk.param.ConfigItemParam;
import com.hbk.service.ISysConfigItemService;
import com.hbk.vo.ConfigItemVo;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
@Transactional
public class SysConfigItemServiceImpl implements ISysConfigItemService {

    @Resource
    private SysConfigItemMapper configItemMapper;

    public CommonResult add(ConfigItemParam.AddParam param){

        SysConfigItem item = configItemMapper.getByCode(param.getCode());
        if(item!=null){
            return Ref.error("code已存在");
        }
        item = new SysConfigItem();
        item.setName(param.getName());
        item.setCode(param.getCode());
        item.setValue(param.getValue());
        item.setCreateTime(new Date());
        item.setUpdateTime(new Date());
        configItemMapper.insert(item);
        return Ref.ok();
    }

    public CommonResult modify(ConfigItemParam.ModifyParam param){
        SysConfigItem item = configItemMapper.selectById(param.getId());
        if(item==null){
            return Ref.error("配置不存在");
        }
        item.setName(param.getName());
        item.setCode(param.getCode());
        item.setValue(param.getValue());
        item.setUpdateTime(new Date());
        configItemMapper.updateById(item);
        return Ref.ok();
    }

    public CommonResult delete(ConfigItemParam.DeleteParam param){
        configItemMapper.deleteById(param.getId());
        return Ref.ok();
    }

    public CommonResult listAll(){
        List<SysConfigItem> itemList = configItemMapper.listAll();
        List<ConfigItemVo.ListAllVo> vos = new ArrayList<>();
        for(int i=0; i<itemList.size(); i++){
            SysConfigItem item = itemList.get(i);
            ConfigItemVo.ListAllVo vo = new ConfigItemVo.ListAllVo();
            vo.setId(item.getId());
            vo.setName(item.getName());
            vo.setCode(item.getCode());
            vo.setValue(item.getValue());
            vo.setCreateTime(TimeUtil.formaterYYYYMMddHHmm(item.getCreateTime()));
            vo.setUpdateTime(TimeUtil.formaterYYYYMMddHHmm(item.getUpdateTime()));
            vo.setIndexNum(i + 1);
            vos.add(vo);
        }
        return Ref.ok(vos);
    }
}
